package com.yyfax.pay.quartz.fixed;

import java.io.Serializable;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.lang3.StringUtils;
import org.quartz.Job;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yyfax.framework.mq.MQConfigure;

/**
 * Quartz服务配置
 */
@SuppressWarnings("serial")
public class QuartzConfigure implements Serializable {

	private static Logger logger = LoggerFactory.getLogger(MQConfigure.class);


	protected static Map<String, QuartzConfigure> configures = new ConcurrentHashMap<String, QuartzConfigure>();

	static {
		// 自动检测quartz.properties文件,并导入配置.
		try {
			PropertiesConfiguration c = new PropertiesConfiguration("quartz.properties"); // classpath目录
			if (c != null) {
				Iterator<String> keys = c.getKeys();
				String key;
				while (keys.hasNext()) {
					key = keys.next();
					if (configures.containsKey(key) || !StringUtils.endsWith(key, ".name")) {
						continue;
					}
					key = key.substring(0, key.length() - 5);
					String name = null;
					Class<Job> job = null;
					String cronEx = null;
					name = c.getString(key.concat(".name"));
					if(StringUtils.isEmpty(c.getString(key.concat(".cron.expression")))){
						throw new Exception(key.concat(".cron.expression") + "配置错误");
					}
					cronEx = c.getString(key.concat(".cron.expression"));
					if(StringUtils.isEmpty(c.getString(key.concat(".job.class")))){
						throw new Exception(key.concat(".job.class") + "配置错误");
					}
					job = (Class<Job>)Class.forName(c.getString(key.concat(".job.class")));
					configures.put(
							key,
							new QuartzConfigure(
									name,
									cronEx,
									job
									));
					logger.info("初始化quartz: {}", configures.get(key));

				}
			}
		} catch (ConfigurationException e) {
			logger.warn("配置{}不存在 ", "quartz.properties");
//			e.printStackTrace();
		}catch (Exception e) {
			e.printStackTrace();
		}
	}

	private final String name;


	private final String cronEx;
	
	private final Class<Job> jobClass;

	public QuartzConfigure(String name, String cronEx, Class<Job> jobClass) {
		this.name = name;
		this.cronEx = cronEx;
		this.jobClass = jobClass;
	}

	public String getName() {
		return name;
	}


	public Class<Job> getJobClass() {
		return jobClass;
	}

	public String getCronEx() {
		return cronEx;
	}
	
	public String getTest(){
		return "";
	}

}
